package com.bprogram.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bprogram.controller.UserFeign;
import com.bprogram.mapper.CommentMapper;
import com.bprogram.pojo.Comment;
import com.bprogram.pojo.User;
import com.bprogram.service.CommentService;

import com.bprogram.utils.IdGenerator;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 评论表 服务实现类
 * </p>
 *
 * @author cai
 * @since 2023-11-21
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Resource
    private CommentMapper commentMapper;
    @Resource
    private UserFeign userFeign;

    @Override
    public IPage<Comment> getCommentListByCondition(long videoId, long upId, String currentPage, String pageSize) {
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(videoId)) {
            wrapper.eq("videoId", videoId);
        }
        if (!StringUtils.isEmpty(upId)) {
            wrapper.eq("upId", upId);
        }
        IPage<Comment> page = new Page<>();
        long ps = Long.parseLong(pageSize);
        long cp = Long.parseLong(currentPage);
        page.setSize(ps);
        page.setCurrent(cp);
        IPage<Comment> commentIPage = commentMapper.selectPage(page, wrapper);
        List<Comment> commentList = commentIPage.getRecords();
        for (int i = 0; i < commentList.size(); i++) {
            User fromUser = userFeign.getById(commentList.get(i).getFromId());
            commentList.get(i).setFromUser(fromUser);
            if (!StringUtils.isEmpty(commentList.get(i).getToId())) {
                User toUser = userFeign.getById(commentList.get(i).getToId());
                commentList.get(i).setToUser(toUser);
            }
        }
        IPage<Comment> pageComment = commentIPage.setRecords(commentList);
        return  pageComment;
    }


    @Override
    public boolean saveComment(Comment comment) {
        IdGenerator idGenerator = new IdGenerator();
        long id = idGenerator.snowflakeId();
        comment.setCommentId(id).setCommentDislike(0l).setCommentLike(0l);
        User loginUser = userFeign.getLoginUser();
        comment.setFromId(loginUser.getUserId());
        return this.save(comment);
    }


}
